<template>
  <div class="app-container">
    <div class="flex justify-between">
      <el-form inline :model="queryParams" class="mt-[20px]" label-width="96px">          
        <el-form-item label="" >
          <el-select
            v-model="queryParams.reportClass"
            style="min-width: 200px"
            placeholder="请选择统计报表"
            @change="HanderChange"
          >
            <el-option  v-for="item in tjbOptions" :label="item.title" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="年度：">
          <el-date-picker
          v-model="queryParams.beginYear"
          type="year" 
          :disabled-date="datePickerOptions"
          placeholder="起始年份" @change="HanderChange"
          style="width: 100px"
        />
        </el-form-item>
        <el-form-item>
          <el-date-picker
          v-model="queryParams.endYear"
          type="year"
          :disabled-date="datePickerOptions"
          placeholder="结束年份" @change="HanderChange"
          style="width: 100px"
        />
        </el-form-item>   
      </el-form>

      <el-button type="primary" class="mt-4" @click="handerExport">
        <!-- <svg-icon iconClass="export" class="mr-[5px]"></svg-icon> -->
        <el-icon :size="20"><Download /></el-icon>
        <span class="text-xs">导出</span>
      </el-button>
      
    </div>
    <el-row :gutter="20">
      <el-col>
        <el-table v-if="tFlag == 1" v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="index" label="序号" width="50" align="center" >
            <template #default="scope"> {{ setNumb(scope.$index) }}</template>
          </el-table-column>
          <template v-for="(item,handIndex) in tableColumn" >
            <el-table-column v-if="!item.children || (item.children && item.children.length == 0)" :key="item.id" :label="item.label" align="center" :prop="item.Field" :show-overflow-tooltip="true" >
              <template #default="scope">
                {{ tableData[scope.$index][item["Field"]] }}
                <!-- <span>{{ scope.$index!== -1 && getField(scope.row,item["Field"]) }}</span>  -->
              </template>
            </el-table-column>
            <template v-else>
              <el-table-column :key="item.id" :label="item.label" align="center" :prop="item.Field" :show-overflow-tooltip="true" >
                    <el-table-column v-for="(sub,ind) in item.children" :key="ind" :label="sub" align="center" :prop="sub" :show-overflow-tooltip="true">
                      <template #default="scope">
                      <!-- <template slot-scope="scope"> -->
                        <!-- {{ tableData[scope.$index][item["Field"]][sub] }} -->
                          {{ getSubData(tableData[scope.$index],item,sub) }}
                      </template>
                    </el-table-column>
              </el-table-column>
            </template>
          </template>
        </el-table>

        <el-table v-else v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="index" label="序号" width="50" align="center" >
            <template #default="scope"> {{ setNumb(scope.$index) }}</template>
          </el-table-column>
          <template  v-for="(item,handIndex) in tableColumn" >
            <el-table-column v-if="!item.children || (item.children && item.children.length == 0)" :key="item.id" :label="item.label" align="center" :prop="item.Field" :show-overflow-tooltip="true" />
            <template v-else >
              <el-table-column :key="item.id" :label="item.label" align="center" :prop="item.Field" :show-overflow-tooltip="true">
                <el-table-column v-for="(sub,ind) in item.children" :label="sub.label" align="center" :prop="sub.Field" :key="sub.id" :show-overflow-tooltip="true" />
              </el-table-column>
            </template>
          </template>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="User">
import {ref,reactive,toRefs,toRaw} from "vue"
import { getToken } from "@/utils/auth";
import useAppStore from '@/store/modules/app'
import { getFixedReport, exportFile } from "@/api/statistics";
import { downloadFile } from "@/utils/main";
import { getItemText, datePickerOptions } from "../../common.js"
import { tjbOptions, columns } from "./index.js"
const router = useRouter();
const appStore = useAppStore()
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict("sys_normal_disable", "sys_user_sex");

const tFlag = ref(0)
const tableColumn = ref([]);
const tableData = ref([]);
const loading = ref(true);
const total = ref(0);

const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    reportClass: 1,//必填
    beginYear: "",
    endYear: ""
});
const getList = ()=>{
  tFlag.value = queryParams.value.reportClass
  let beginYear = queryParams.value.beginYear ? new Date(queryParams.value.beginYear).getFullYear(): ''
  let endYear = queryParams.value.endYear ? new Date(queryParams.value.endYear).getFullYear() : ""
  let params = {
    ...queryParams.value
  }  
  tableColumn.value = columns[`column${queryParams.value.reportClass}`]
  if(queryParams.value.reportClass !== 3){
    if(!beginYear && !endYear){
      beginYear = new Date().getFullYear()
      endYear = new Date().getFullYear()
    } else if(!beginYear && endYear){
      beginYear = endYear
    } else if(beginYear && !endYear){
      endYear = beginYear
    }
    const n = endYear - beginYear
    if(n<0){
      queryParams.value.endYear = ""
      proxy.$modal.msgSuccess("起始年份选择不符合要求！")
      return
    } else{
      // 分类处理 表头数据
      if(queryParams.value.reportClass == 1){
        let years = []
        for(let i=0; i<=n;i++){
          years.push(beginYear+i)
        }
        tableColumn.value.forEach(ele => {
          if(ele.childFlag){
            ele.children = years
          }
        });  
      } else if(queryParams.value.reportClass == 2){
        let column2 = [].concat(columns[`column${queryParams.value.reportClass}`])
        for(let i=0; i<=n; i++){
          column2.push({
            id: i+1, 
            label: beginYear+i, 
            Field:beginYear+i, 
            childFlag: false
          })
        }
        tableColumn.value = column2
      }
    }    
    params.beginYear = beginYear,
    params.endYear = endYear
  }
  // console.log(column)

  loading.value = true;
  getFixedReport(proxy.addDateRange(params)).then((res) => {
    loading.value = false;
    tableData.value = res.rows
    total.value = res.total;
  })
  .catch((error) => {
    loading.value = false;
    console.log(error);
  });
}
const HanderChange = (row)=>{
  queryParams.value.pageNum = 1
  getList()
}
const getField = (row,field)=>{
  return row[field]
}
const getSubData = (scope,item,sub)=>{
// 判单field字段是否存在，否则报错
  return scope[item["Field"]]?.[sub] 
}
const setNumb = (index)=>{
  return (queryParams.value.pageNum-1) * queryParams.value.pageSize + index +1 
}
const handerExport = ()=>{
  let beginYear = queryParams.value.beginYear ? new Date(queryParams.value.beginYear).getFullYear(): ''
  let endYear = queryParams.value.endYear ? new Date(queryParams.value.endYear).getFullYear() : ""

  if(!beginYear && !endYear){
    beginYear = new Date().getFullYear()
    endYear = new Date().getFullYear()
  } else if(!beginYear && endYear){
    beginYear = endYear
  } else if(beginYear && !endYear){
    endYear = beginYear
  }
  const {reportClass} = queryParams.value
  let params = {
    reportClass,
    beginYear,
    endYear
  }  
  loading.value = true;
  exportFile("/statistics/fixedReportExport",params).then((res) => {
    loading.value = false;
    downloadFile(res, `${getItemText(tjbOptions,reportClass,"title")}_${new Date().getTime()}.xlsx`);
  })
  .catch((error) => {
    loading.value = false;
    console.log(error);
  });
  // 下载的 全局方法
  // proxy.download("/statistics/fixedReportExport",  params, `user123_${new Date().getTime()}.xlsx`);
}
getList();
</script>
